package com.wolfsea.drageventdemo
import android.content.ClipData
import android.content.ClipDescription
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.DragEvent
import android.view.View
import android.view.View.OnDragListener
import android.view.View.OnLongClickListener
import com.wolfsea.drageventdemo.databinding.ActivityMainBinding

class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {

    override fun init(savedInstanceState: Bundle?) {

        mBinding.imageview.setOnLongClickListener(OnLongClickListener { v -> //创建移动数据
            val item = ClipData.Item("abc")
            val data = ClipData("IMAGEVIEW_TAG", arrayOf(ClipDescription.MIMETYPE_TEXT_PLAIN), item)
            //调用startDrag方法,第二个参数为创建拖放阴影
            v.startDragAndDrop(data, View.DragShadowBuilder(v), null, 0)
            true
        })


        mBinding.container.setOnDragListener(OnDragListener { v, event ->
            when (event.action) {
                DragEvent.ACTION_DRAG_STARTED -> {
                    //拖拽开始事件
                    Log.d(TAG,"DragEvent.ACTION_DRAG_STARTED")
                    return@OnDragListener event.clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)
                }
                DragEvent.ACTION_DRAG_ENTERED -> {
                    //被拖放View进入目标View
                    Log.d(TAG,"DragEvent.ACTION_DRAG_ENTERED")
                    mBinding.container.setBackgroundColor(Color.YELLOW)
                    return@OnDragListener true
                }
                DragEvent.ACTION_DRAG_LOCATION -> {
                    Log.d(TAG,"DragEvent.ACTION_DRAG_LOCATION")
                    return@OnDragListener true
                }
                DragEvent.ACTION_DRAG_EXITED -> {
                    //被拖放View离开目标View
                    Log.d(TAG,"DragEvent.ACTION_DRAG_EXITED")
                    mBinding.container.setBackgroundColor(Color.BLUE)
                    mBinding.title.text = ""
                    return@OnDragListener true
                }
                DragEvent.ACTION_DROP -> {
                    //释放拖放阴影，并获取移动数据
                    Log.d(TAG,"DragEvent.ACTION_DROP")
                    val item = event.clipData.getItemAt(0)
                    val dragData = item.text.toString()
                    mBinding.title.text = dragData
                    return@OnDragListener true
                }
                DragEvent.ACTION_DRAG_ENDED -> {
                    //拖放事件完成
                    Log.d(TAG,"DragEvent.ACTION_DROP")
                    return@OnDragListener true
                }
                else -> {}
            }
            false
        })
    }

    companion object {
        const val TAG = "MainActivity"
    }

}